<?php

namespace app\home\business;

use app\home\model\Cart;
use think\facade\Cookie;

class CartBusiness
{
    public static function addCart($goods_id,$goodsSpecId,$number,$is_selected){
        // 判断是否登录
        if (session('?userInfo')){
            // 登录存入数据库
            $user_id=session('userInfo.id');
            // 查询用户是否有这件商品
            $cart=Cart::where('goods_id',$goods_id)
                ->where('spec_goods_id',$goodsSpecId)
                ->where('user_id',$user_id)
                ->find();
            if (!$cart){
                $cart_arr=[
                    'number'=>$number,
                    'user_id'=>$user_id,
                    'goods_id'=>$goods_id,
                    'spec_goods_id'=>$goodsSpecId,
                    'is_selected'=>$is_selected
                ];
                Cart::create($cart_arr);
            }else{
                // 购物车已有此商品
                $cart_data['number']=$cart['number']+$number;
                Cart::update($cart_data,['id'=>$cart['id']]);

            }
        }else{
            // 未登录存入cookie
            $cart=cookie('cart')?:[];
            // 组装存储cookie的键
            $key=$goodsSpecId;
            // 判断cookie中是否有同类型商品
            $cart_arr=unserialize($cart);
            if (isset($cart_arr["$key"])){
                // 购物车中有这件商品 更改商品类型
                $cart_arr[$key]['number']+=$number;
            }else{
                $cart_arr["$key"]=[
                    'number'=>$number,
                    'is_selected'=>$is_selected
                ];
            }
            cookie('cart',serialize($cart_arr));



        }





    }
}